/**
 * 
 */
package junior.db.mapping;

import org.springframework.util.StringUtils;

/**
 * @author bo.wu
 * @CreateDate 2015年6月2日
 */
public class CamelCaseColumnMapping implements ColumnMapping {
	private String fieldPrefix = "";
	private String fieldSuffix = "";
	private String columnPrefix = "";
	private String columnSuffix = "";
	
	public String getFieldPrefix() {
		return fieldPrefix;
	}
	public void setFieldPrefix(String fieldPrefix) {
		this.fieldPrefix = fieldPrefix;
	}
	public String getFieldSuffix() {
		return fieldSuffix;
	}
	public void setFieldSuffix(String fieldSuffix) {
		this.fieldSuffix = fieldSuffix;
	}
	public String getColumnPrefix() {
		return columnPrefix;
	}
	public void setColumnPrefix(String columnPrefix) {
		this.columnPrefix = columnPrefix;
	}
	public String getColumnSuffix() {
		return columnSuffix;
	}
	public void setColumnSuffix(String columnSuffix) {
		this.columnSuffix = columnSuffix;
	}

	@Override
	public String field2Column(Class<?> entityClass, String fieldName) {
		if (StringUtils.hasText(fieldPrefix) && fieldName.startsWith(fieldPrefix)) {
			fieldName = fieldName.substring(fieldPrefix.length());
		}

		if (StringUtils.hasText(fieldSuffix) && fieldName.endsWith(fieldSuffix)) {
			fieldName = fieldName.substring(0, fieldName.length() - fieldSuffix.length());
		}
		
		char[] fieldArrays = fieldName.toCharArray();
		StringBuilder buffer = new StringBuilder();
		for(char c : fieldArrays) {
			if(Character.isUpperCase(c)) { //大写字母
				buffer.append("_");
				buffer.append(Character.toLowerCase(c));
			} else {
				buffer.append(c);
			}
		}
		return columnPrefix + buffer.toString() + columnSuffix;
	}

	@Override
	public String column2Field(String tableName, String columnName) {
		if (StringUtils.hasText(columnPrefix) && columnName.startsWith(columnPrefix)) {
			columnName = columnName.substring(columnPrefix.length());
		}

		if (StringUtils.hasText(columnSuffix) && columnName.endsWith(columnSuffix)) {
			columnName = columnName.substring(0, columnName.length() - columnSuffix.length());
		}
		
		if (columnName.length() > 1) {
			if (Character.isUpperCase(columnName.charAt(0))) {
				columnName = columnName.toLowerCase();
			}
			
			if (columnName.contains("_")) {
				String[] spt = columnName.toLowerCase().split("_");
				StringBuilder buffer = new StringBuilder();
				buffer.append(spt[0]);
				for (int i = 1; i < spt.length; i++) {
					buffer.append(StringUtils.capitalize(spt[i]));
				}
				columnName = buffer.toString();
			}
		}
		return fieldPrefix + columnName + fieldSuffix;
	}

}
